/**
 * @date: 2025/3/22
 * @author: 小红
 * @fileName: 请求 helper
 */

/**
 * @description: 获取默认请求头
 */
import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { API_CODE, AUTHORIZATION_KEY, AUTHORIZATION_PREFIX, type ExpandConfig, TENANT_ID, VERSION } from '@/utils/http/types.ts';
import { Message } from '@arco-design/web-vue';
import { useUserStore } from '@/stores/modules/user.ts';
import { useAuthStore } from '@/stores/modules/auth.ts';
import { useEnv } from '@/hooks/useEnv.ts';
import { resetAllStores } from '@/stores';
import { router } from '@/router';

/**
 * 鉴权的header
 */
export function getAuthHeader() {
	const userStore = useUserStore();
	const authStore = useAuthStore();

	const headers: any = {};

	if (userStore.tenant) {
		headers[TENANT_ID] = userStore.tenant.id;
	}

	if (authStore.accessToken) {
		headers[AUTHORIZATION_KEY] = AUTHORIZATION_PREFIX + authStore.accessToken;
	}
	headers[VERSION] = useEnv('VITE_APP_VERSION');

	return headers;
}

/**
 *  请求拦截
 */
export function createRequestInterceptors(config: InternalAxiosRequestConfig & ExpandConfig) {
	// 为方便业务中的请求的 loading 可以直接传入
	if (config?.loading) {
		config.loading.value = true;
	}

	Object.assign(config.headers, getAuthHeader());

	return config;
}

/**
 * 响应拦截
 */
export function createResponseInterceptors(response: AxiosResponse) {
	const config = response.config as InternalAxiosRequestConfig & ExpandConfig;

	if (config?.loading) {
		config.loading.value = false;
	}

	/**
	 * 未登录 无权限
	 */
	if ([API_CODE.noAuth].includes(response.data.code)) {
		Message.error('登录失效，请重新登录');
		resetAllStores(() => {
			router.replace({ path: '/login' });
		});
		return Promise.reject(response);
	}

	/**
	 *  正常情况
	 */
	if (![200, API_CODE.success].includes(response.data.code)) {
		Message.error(response.data.msg);
		return Promise.reject(response);
	}

	/**
	 * 业务异常
	 */

	return config.allResponses ? response : response.data?.data;
}

/**
 * 异常处理
 */
export function createError(error: any) {
	if (error?.config?.loading) {
		error.config.loading.value = false;
	}

	Message.error(error.response?.data.msg || '服务器错误,请联系管理员');

	if ([API_CODE.error].includes(error.status)) {
		resetAllStores(() => {
			router.replace({ path: '/login' });
		});
	}

	return Promise.reject(error);
}
